package com.xiang.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: xiang
 * Date: 2021/9/13 11:02
 */
@Controller
@RequestMapping(value = "/file")
public class FileUploadController {
//    @RequestMapping(value = "/up", method = RequestMethod.POST)
//    public String uploadFile(@RequestParam("imgPath") MultipartFile file, Model model, MultipartHttpServletRequest request) throws Exception {
//        //判断目录是否在服务器上，如果没有我们创建一个目录，并把上传文件放在目录下面
//        if (!file.isEmpty()) {
//            String imgPath =
//                    request.getSession().getServletContext().getRealPath("")
//                    + file.getOriginalFilename();
//            System.out.println(imgPath);
//            //上传文件到指定目录
//            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(imgPath));
//            model.addAttribute("url",imgPath);
//        }
//        return "view/res";
//    }
    @RequestMapping(value = "/up2", method = RequestMethod.POST)
    public  String  uploadFile2(@RequestParam("imgPath") MultipartFile imgPath, Model model, HttpServletRequest request) throws IOException {
        String realPath = request.getSession().getServletContext().getRealPath("/upload/");
        File dir = new File(realPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        // 获取文件名
        String originalFilename = imgPath.getOriginalFilename();
        // 文件存储位置
        File file =new File(dir,originalFilename);
        //  文件保存
        imgPath.transferTo(file);
            /*//上传图片
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File(imgPath));*/
        System.out.println(file);
//            model.addAttribute("")
        model.addAttribute("url",file);
        model.addAttribute("name",originalFilename);
        return "view/res";
    }

}



